<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24" v-if="deptId==101">
        <div class="head-container">
          <el-input v-model="deptName" placeholder="请输入部门名称" clearable prefix-icon="Search" style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree :data="deptOptions" :props="{ label: 'label', children: 'children' }" :expand-on-click-node="false" :filter-node-method="filterNode"
            ref="deptTreeRef" node-key="id" highlight-current default-expand-all @node-click="handleNodeClick" />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="deptId!=101?24:20" :xs="24">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="用户名称" prop="userName">
            <el-input v-model="queryParams.userName" placeholder="请输入用户名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="岗位" prop="postId">
            <el-select v-model="queryParams.postId" placeholder="请选择">
              <el-option v-for="item in postOptions" :key="item.postId" :label="item.postName" :value="item.postId"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['userManage:user:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['userManage:user:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['userManage:user:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Upload" @click="handleImport" v-hasPermi="['userManage:user:import']">导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['userManage:user:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <Custable :loading="loading" :content="baseConfig.goOutContent" :list="userList" :queryParams="queryParams" :total="total" @getList="getList">
          <template #operation="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['userManage:user:edit']">修改</el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['userManage:user:remove']">删除</el-button>
            </el-tooltip>
            <el-tooltip content="调动" placement="top" v-hasPermi="['userManage:user:edit']">
              <el-button link type="primary" icon="Switch" @click="handleTransfer(scope.row)">调动</el-button>
            </el-tooltip>
          </template>

        </Custable>

      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <free-form ref="addFormRef" formRef="formRef" :rules="rules" :model="form" :formItemConfig="baseConfig.formItemConfig" @parent-event="handleParentEvent"
        @getformModel="getformModel" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 调用用户 -->
    <el-dialog title="人员调用" v-model="dialogTransfer" width="1000px" append-to-body>
      <free-form ref="addFormTransferRef" formRef="formRefTransfer" :rules="rulesTransfer" :model="rowDetails"
        :formItemConfig="baseConfig.formItemTransferConfig" @parent-event="handleParentEvent" @getformModel="getformTransferModel" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitTransferForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 用户审核或者打印 -->
    <Details :dialogVisible="isDetails" :rowDetails="rowDetails" :dialogApproval="dialogApproval" @handleClose="handleClose">
      <template #footer="scope">
        <el-form :model="formApproval" label-width="120px" ref="refApproval" :rules="rulesApproval">
          <el-form-item label="选择" prop="status">
            <el-radio-group v-model="formApproval.status" class="ml-4" @change="bindChangeForm('status',$event)">
              <el-radio label="待分管领导审批" size="large">同意</el-radio>
              <el-radio label="已驳回" size="large">驳回</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="请填写理由" prop="opinions">
            <el-input v-model="formApproval.opinions" type="textarea" placeholder="请填写理由" @input="bindChangeForm('opinions',$event)" :rows="5" />
          </el-form-item>
          <el-form-item label="审批人" prop="approval" v-if="!isLast">
            <el-select v-model="formApproval.approval" @change="bindChangeForm('approval', $event)" style="width:100%">
              <el-option v-for="(option) in manageList" :key="option.value" :label="option.label" :value="option.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div class="dialog-footer flex-right">
          <el-button type="primary" @click="submitFormApproval">提交</el-button>
          <el-button @click="handleClose">取 消</el-button>
        </div>
      </template>
    </Details>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="User">
import { getToken } from "@/utils/auth";
import { pcaTextArr } from "element-china-area-data";
import { changeUserStatus, listUser, resetUserPwd, delUser, updateUser, addUser, deptTreeSelect } from "@/api/system/user";
import { getCharge, listCharge, addCharge, updateCharge, delCharge, postDefinitionStart, getUser } from "@/api/charge/charge";
import { getNextFlowNodeByStart, completeTask } from "@/api/flowable/todo";
import FreeForm from "@/components/Custom/FreeForm";
import Custable from "@/components/Custom/Custable";
import Details from "./components/Details";
import baseConfig from "./config";
import { config } from "../../../components/Process/common/bpmnlintconfig";
import { getCKInfo } from '@/utils/auth'
const { proxy } = getCurrentInstance();
const { nature_type } = proxy.useDict('nature_type');

const addFormRef = ref({});
const addFormTransferRef = ref();
const userList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const deptName = ref("");
const deptOptions = ref(undefined);
const initPassword = ref(undefined);
const postOptions = ref([]);
const isDetails = ref(false);
const rowDetails = ref({})
const dialogTransfer = ref(false)
const dialogApproval = ref(false);
const wholeName = ref([])
const userName = ref('')
const deptId = ref(Number(getCKInfo('deptId')))
const roleOptions = ref([]);/*** 用户导入参数 */
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/employee/importData"
});
// 列显隐信息
const columns = ref([
  { key: 0, label: `用户编号`, visible: true },
  { key: 1, label: `用户名称`, visible: true },
  { key: 2, label: `用户昵称`, visible: true },
  { key: 3, label: `部门`, visible: true },
  { key: 4, label: `手机号码`, visible: true },
  { key: 5, label: `状态`, visible: true },
  { key: 6, label: `创建时间`, visible: true }
]);

const data = reactive({
  form: {},
  formTransfer: { sourcedeptId: '' },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
    companyId: undefined,
    deptId: undefined,
    postId: undefined,
  },
  formApproval: {},
  rules: {
    phonenumber: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }, { required: true, message: "手机号码不能为空", trigger: "blur" }],
    deptId: [{ required: true, message: "部门不能为空", trigger: "blur" }],
    userName: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
    companyId: [{ required: true, message: "公司不能为空", trigger: "blur" }],
    postId: [{ required: true, message: "岗位不能为空", trigger: "blur" }],
  }, rulesTransfer: {
    deptName: [{ required: true, message: "部门不能为空", trigger: "blur" }],
    userName: [{ required: true, message: "用户不能为空", trigger: "blur" }],
    postId: [{ required: true, message: "岗位不能为空", trigger: "blur" }],
  }

});

const { queryParams, form, rules, formApproval, formTransfer, rulesTransfer } = toRefs(data);

if (pcaTextArr) {
  baseConfig.formItemConfig[5].options = pcaTextArr;
  baseConfig.formItemConfig[6].options = pcaTextArr
}
/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

/** 根据名称筛选部门树 */
watch(deptName, val => {
  proxy.$refs["deptTreeRef"].filter(val);
});
/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;


    baseConfig.formItemConfig.forEach(item => {
      // if (item.prop == 'wholeNameArr') {
      //   item.options = response.data;
      //   item.onChange = (val) => {
      //     form.value.companyId = val[0];
      //     form.value.deptId = val[val.length - 1];
      //     form.value.wholeNameArr = val;
      //   };
      // }
      // if (item.prop == 'nation') {
      //   item.options=[]
      //   baseConfig.national.forEach(opt => {
      //     item.options.push({ label: opt, value: opt })
      //   })
      // }

      if (item.prop == 'natureOfEmployment') {
        item.options = nature_type.value
      }

    })
  
    baseConfig.formItemTransferConfig[3].options = response.data;
    baseConfig.formItemTransferConfig[3].onChange = (val) => {
      getList(val.id)
    };
    baseConfig.formItemTransferConfig[5].options = response.data;


  });
};
/** 查询岗位结构 */
function getPostTree() {
  getUser().then(response => {
    postOptions.value = response.data;
    let arr = [];

    // baseConfig.formItemConfig[3].options = [];
    baseConfig.formItemTransferConfig[2].options = [];
    baseConfig.formItemTransferConfig[4].options = [];
    response.data.forEach(element => {
      arr.push({ label: element.postName, value: element.postId, key: element.postId })

    });
    baseConfig.formItemConfig.forEach(item => {
      if (item.prop == 'postId') {
        item.options = arr
      }
    })
    // baseConfig.formItemConfig[3].options.push({ label: element.postName, value: element.postId, key: element.postId })
    baseConfig.formItemTransferConfig[2].options=arr;
    baseConfig.formItemTransferConfig[4].options=arr;
  })
};
/** 查询用户列表 */
function getList(deptId) {
  loading.value = true;
  listCharge(deptId ? { deptId, pageNum: 1, pageSize: 999 } : proxy.addDateRange(queryParams.value, dateRange.value)).then(res => {
    if (deptId) {
      baseConfig.formItemTransferConfig[2].options = []
      baseConfig.formItemTransferConfig[4].options = []
      res.rows.forEach(item => {
        baseConfig.formItemTransferConfig[2].options.push({ label: item.userName, value: item.id })
        baseConfig.formItemTransferConfig[4].options.push({ label: item.userName, value: item.id })
      }
      )

    } else {
      loading.value = false;

      total.value = res.total;
      userList.value = res.rows;
    }

  });
};
/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams.value.deptId = data.id;
  handleQuery();
};
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  queryParams.value.deptId = undefined;
  proxy.$refs.deptTreeRef.setCurrentKey(null);
  handleQuery();
};
/** 删除按钮操作 */
function handleDelete(row) {
  const userIds = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function () {
    return delCharge(userIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
};
/** 导出按钮操作 */
function handleExport() {
  proxy.download("/employee/export", {
    ...queryParams.value,
  }, `人员管理_${new Date().getTime()}.xlsx`);
};
/** 用户状态修改  */
function handleStatusChange(row) {
  let text = row.status === "0" ? "启用" : "停用";
  proxy.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗?').then(function () {
    return changeUserStatus(row.id, row.status);
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(function () {
    row.status = row.status === "0" ? "1" : "0";
  });
};

/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.userId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
/** 导入按钮操作 */
function handleImport() {
  upload.title = "用户导入";
  upload.open = true;
};
/** 下载模板操作 */
function importTemplate() {
  proxy.download("/employee/importTemplate", {
  }, `user_template_${new Date().getTime()}.xlsx`);
};
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};
/** 重置操作表单 */
function reset() {
  form.value = {
    userId: undefined,
    deptId: undefined,
    userName: undefined,
    userName: undefined,
    password: undefined,
    phonenumber: undefined,
    email: undefined,
    sex: undefined,
    status: "0",
    remark: undefined,
    postIds: [],
    roleIds: []
  };
  proxy.resetForm("userRef");
};
/** 取消按钮 */
function cancel() {
  open.value = false;
  dialogTransfer.value = false;
  reset();
};

/** 新增按钮操作 */
function handleAdd() {
  reset();
  if (deptId.value != 101 && baseConfig.formItemConfig.length == 10) {
    baseConfig.formItemConfig.splice(2, 1)
  }

  if (deptId.value == 101 && baseConfig.formItemConfig.length == 9) {
    baseConfig.formItemConfig.splice(2, 0, {
      label: "公司/部门",
      prop: "wholeNameArr",
      component: "cascader", // 可以传入任意组件
      placeholder: "请选择",
      clearable: true,
      width: "100%", // 设置宽度
      span: 12, // 使用栅格布局
      options: deptOptions.value,
      key: "deptId",
      labelWidth: "100px",
      props: { label: "label", value: "id" },
    },)
  }

  form.value = {};
  open.value = true;
  title.value = "添加用户";
};
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  if (deptId.value != 101 && baseConfig.formItemConfig.length == 10) {
    baseConfig.formItemConfig.splice(2, 1)
  }

  if (deptId.value == 101 && baseConfig.formItemConfig.length == 9) {
    baseConfig.formItemConfig.splice(2, 0, {
      label: "公司/部门",
      prop: "wholeNameArr",
      component: "cascader", // 可以传入任意组件
      placeholder: "请选择",
      clearable: true,
      width: "100%", // 设置宽度
      span: 12, // 使用栅格布局
      options: deptOptions.value,
      key: "deptId",
      labelWidth: "100px",
      props: { label: "label", value: "id" },
    },)
  }

  const userId = row.id || ids.value;
  getCharge(userId).then(response => {
    response.data.wholeNameArr = []
    response.data.address = response.data.address ? response.data.address.split(",") : ''
    response.data.nativePlace = response.data.nativePlace ? response.data.nativePlace.split(",") : ""
    let wholeNameArr = response.data.wholeName ? response.data.wholeName.split(",") : "";
    wholeNameArr.forEach(item => {
      response.data.wholeNameArr.push(Number(item))
    })
    // =wholeNameArr
    form.value = response.data;
    open.value = true;
    title.value = "修改用户";
  });
};
/** 提交按钮 */
function submitForm() {
  addFormRef.value?.accountLoginAction();
}
function submitTransferForm() {
  // 用户调动 transfer2 用户 transfer4 transfer3 调入部门调出部门
  // let data={deployId:1077555,procDefId:'flow_c3inpdn2:8:1077558',variables:{transfer2:"yonghu ",transfer3:"yonghu ",transfer4:"yonghu "},formData:{transfer2:"yonghu ",transfer4:"yonghu ",transfer4:"yonghu "}}
  // getNextFlowNodeByStart(data).then(res=>{
  //   if(res.code==200){
  //     postDefinitionStart(data).then(respon=>{
  //         if(respon.code==200){

  //         }
  //     })
  //   }
  // })
  addFormTransferRef.value?.accountLoginAction();
}

function getformTransferModel(valid) {
  if (valid) {
    let postdata = {
      transferDate: rowDetails.value.transferDate, deptId: rowDetails.value.deptId, transferDeptId: form.value.transferDeptId, userId: rowDetails.value.id, postId: rowDetails.value.postId,
      deptName: rowDetails.value.deptName, transferDeptName: form.value.transferDeptName, postName: rowDetails.value.postName, userName: rowDetails.value.userName, phonenumber: rowDetails.value.phonenumber,transferPostId:rowDetails.value.transferPostId
    }
    let data = { "deployId": "1115001", "procDefId": "flow_c3inpdn2:13:1115004", "checkedAssignMap": {}, "comment": "123", "variables": postdata, "formData": postdata }
    postDefinitionStart(data).then(response => {
      proxy.$modal.msgSuccess("调用成功");
      dialogTransfer.value = false;
      getList();
    });

    // });
  }
};

const submitFormApproval = () => {
  // 审核提交
  let postdata = {
    transferDate: rowDetails.value.transferDate, deptId: rowDetails.value.deptId, transferDeptId: rowDetails.value.transferDeptId, userId: rowDetails.value.id, postId: rowDetails.value.postId,
    transfer2: rowDetails.value.id, transfer3: rowDetails.value.transferDeptId, transfer4: rowDetails.value.deptId,transferPostId:rowDetails.value.transferPostId
  }
  let data = { "deployId": "1077555", "taskId": "1087550", executionId: "1087536", procDefName: "人员调动", procInsId: "1087527", taskName: "调出部门负责人审批", "variables": postdata, "formData": postdata }
  postDefinitionStart(data).then(response => {
    proxy.$modal.msgSuccess("调用成功");
    dialogTransfer.value = false;
    getList();
  });
}
function getformModel(valid) {
  if (valid) {
    
   
    if( form.value.address){form.value.address = form.value.address.join(',');}
    if(form.value.nativePlace ){ form.value.nativePlace = form.value.nativePlace.join(',')}
    if(form.value.wholeName){
      form.value.wholeName = form.value.wholeNameArr.join(',')
    }
   
    if (form.value.id != undefined) {
      updateCharge(form.value).then(response => {
        proxy.$modal.msgSuccess("修改成功");
        open.value = false;
        getList();
      });
    } else {
      addCharge(form.value).then(response => {
        proxy.$modal.msgSuccess("新增成功");
        open.value = false;
        getList();
      });
    }
  }
};
const handleParentEvent = (data) => {
  // 处理自定义事件的逻辑
  if (data.name == 'transferDeptId') {
    form.value[data.name] = data.id;
    form.value.transferDeptName = data.val;
  } else {
    form.value[data.name] = data.val;
  }


}

// 详情
const handleShow = (data) => {
  rowDetails.value = data;
  isDetails.value = true;
}

const handleTransfer = (data) => {
  rowDetails.value = data;
  dialogTransfer.value = true;
}

getPostTree()
getDeptTree();
getList();
</script>


<style>
.content-cus .el-descriptions__cell {
  border: none !important;
}
.border-top {
  border-top: 1px solid #ebeef5;
}
.padding-none {
  padding: 0 !important;
}
.coumn-cus {
  padding: 8px 11px;
  min-height: 43px;
}
.flex-between {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.text-right {
  text-align: right;
}
</style>